package com.CGFrame.struts.bean.roleAuth;

import java.text.SimpleDateFormat;
import java.util.*;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.CGFrame.struts.POJOs.Authority;
import com.CGFrame.struts.POJOs.Company;
import com.CGFrame.struts.POJOs.Role;
import com.CGFrame.struts.POJOs.Authorityrole;
import com.CGFrame.struts.bean.ProjectOperate;
import com.CGFrame.struts.bean.ProjectOperateFactory;

public class RoleBean {
	
	
	
	public  List<Authority> UpdateRole(Integer roleId,String roleName,Company company, String illumination,String canViewPrj,String [] authorities,String [] manages) throws Exception
	{
		
		short canViewAllPrj = (short)Integer.parseInt(canViewPrj);
		ProjectOperate pop = ProjectOperateFactory.getprojectOperate();
	//	Role r = (Role)pop.UniqueQuery("Role", "roleId,"+roleId);
		Role role = new Role();
		if (roleId!=null)  role = (Role)pop.UniqueQuery("Role", "roleId,"+roleId);//roleId 为null时候，为添加role,不设置RoleID
		else if (roleName!=null && company!=null)
		{
			//新role需要roleName company
			role.setRoleName(roleName);
			role.setCompany(company);
		}
		else
		{
			throw new Exception("UpdateRole  argument Error");
		}
		role.setIllumation(illumination);
		role.setCanViewAllPrj(canViewAllPrj);
		
		pop.saveObject(role);
		
		List<Authority> modAuthorities = new ArrayList<Authority>(); //存修改后的Authorities 用来返回
		
		boolean HasManage = true; //有无管理项标志
		List<String> list_Manages = new ArrayList<String>();
		try {
			list_Manages = Arrays.asList(manages); // 优化比较算法
		} catch (Exception e) {
			HasManage = false; // 有异常说明不管理项
		}
		
		for(Iterator it = role.getAuthorityroles().iterator();it.hasNext();)
		{
			Authorityrole athr = (Authorityrole)it.next();
			pop.delete(athr);
		}
		if ( authorities == null)
		{
			return null ;
		}
		for(int i=0;i<authorities.length;i++)
		{
			Authorityrole athre = new Authorityrole();
			Authority auth = (Authority)pop.UniqueQuery("Authority", "authorityId,"+authorities[i]);
			athre.setAuthority(auth);
			athre.setRole(role);
			if (HasManage && list_Manages.contains(authorities[i]))
			{
				athre.setManage( (short)1 );				
			}
			pop.saveObject(athre);
			modAuthorities.add(auth);
		}
		return modAuthorities;
	}
	
	
	
	
}